<template>
  <div class="app-container">
    <el-row :gutter="20" style="height: 800px">
      <!--用户数据-->
      <el-card class="box-card" style="width: 500px; float: left; height: 800px">
        <div slot="header" class="clearfix">
          <span>贷款的学生</span>
          <el-button style="float: right; padding: 3px 0" @click="resetQuery" type="text">重置</el-button>
        </div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="130px">
          <el-form-item prop="phonenumber" label="请输入机号码搜索">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 210px"
              @keyup.enter.native="handleQuery"
            />
            <el-button style="margin-left: 20px" type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-col :span="24" :xs="24" style="float: left">

            <div slot="header" class="clearfix">
              <span>贷款的学生</span>
              <el-button style="float: right; padding: 3px 0" @click="resetQuery" type="text">重置</el-button>
            </div>
            <el-table @row-click="rowClick" :cell-style="{padding:'10px'}" v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="学生姓名" prop="userName" width="120" align="center" />
              <el-table-column label="学生昵称" align="center" prop="nickName" />
              <el-table-column label="手机号码" align="center" prop="phonenumber" width="180" />
              <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
        </el-col>
       </el-card>

      <el-card class="box-card" style="width: 500px; float: left; margin-left: 20px">
        <div slot="header" class="clearfix">
          <span>逾期情况</span>
          <el-button style="float: right; padding: 3px 0" @click="resetQuery" type="text">重置</el-button>
        </div>
        <el-table
          ref="refTable"
          v-loading="loading" :data="expireList" @selection-change="handleSelectionChange">
          <el-table-column width="120" label="年度" align="center" prop="duringYear" fixed="left" />
          <el-table-column width="120" label="借款金额/元" align="center" prop="contract.firstBorrowMoney" />
          <el-table-column width="120" label="借款账户" align="center" prop="contract.accountName" />
          <el-table-column width="120" label="借款年限" align="center" prop="contract.borrowLimitYear" />
          <el-table-column width="180" label="借款人联系方式" align="center" prop="contract.firstPhone" />
          <el-table-column width="120" label="借款人联系邮编" align="center" prop="contract.firstPostCode" :show-overflow-tooltip="true" />
          <el-table-column width="180" label="贷款到期时间" align="center" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              {{ scope.row.contract.toYear }}年{{ scope.row.contract.toMonth }}月{{ scope.row.contract.toDay }}日
            </template>
          </el-table-column>
          <el-table-column width="120" label="是否逾期" align="center" fixed="right" prop="isExpireForPay" >
            <template slot-scope="scope">
              <el-tag :type="scope.row.isExpireForPay === '已逾期' ? 'danger' : scope.row.isExpireForPay === null ? 'success' : 'success' " effect="dark">{{ scope.row.isExpireForPay ? scope.row.isExpireForPay : '未逾期' }}</el-tag>
            </template>
          </el-table-column>
        </el-table>

      </el-card>

    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="nickName">
              {{form.userName}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              {{form.nickName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              {{form.phonenumber}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              {{form.email}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              {{form.userName}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              {{form.password}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listUser, getUser, delUser, addUser, updateUser, exportUser, resetUserPwd, importTemplate } from "@/api/system/user";
  import { getToken } from "@/utils/auth";
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { selectUserListForStudent } from '../../../api/system/user'
  import { getCredits } from '../../../api/county/credit'
  import { getRepaysByCreditId, selectRepayByMaxDate } from '../../../api/alipay/repay'
  import { formatDate } from '../../../utils/date'

  export default {
    name: "User",
    components: { Treeselect },
    data() {
      return {
        expireList: [],
        isExpireTime: '',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 6,
          phonenumber: undefined,
        },
        // 表单校验
        rules: {}
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getTreeselect();
    },
    methods: {
      rowClick(data) {
        getCredits(data.userName).then(response => {
          console.log(response)
          this.expireList = response.data
         })
      },
/*      clickTable(row,index,e) {
        this.$refs.refTable.toggleRowExpansion(row)
        getRepaysByCreditId(row.creditId).then(res => {
          this.repayList = res.repayList
          // 遍历每次还款金额，求合计
          for (let i in this.repayList) {
            this.sum += parseInt(this.repayList[i].repayMoney)
            this.reverseSum = parseInt(row.contract.firstBorrowMoney) - parseInt(this.sum)
          }

          // 通过指定范围内repayId,这个repayId是credit表中有多个repayId,在准确的范围内的repayId查询最大时间的记录
          var formData = new FormData()
          formData.append('startRepayId', this.repayList[0].repayId)
          formData.append('endRepayId', this.repayList[this.repayList.length - 1].repayId)
          selectRepayByMaxDate(formData).then(res => {
            console.log(res)
            // 我后端是用List返回的,因为可能会有时间相同的多条支付记录
            // 如果有多条相同记录，选第一个就好了，时间是相同的
            if (res.maxDateList.length > 1) {
              const maxDate = res.maxDateList[0].repayDate
              // 最大时间如果超过当前时间，那么就是逾期还款支付

            }
            console.log('记录中的最大时间 ' + res.maxDateList[0].repayDate)
            console.log('当前时间 ' + new Date())

            // 最大日期格式化
            let date = new Date(res.maxDateList[0].repayDate)
            const newMaxDate = formatDate(date, 'yyyy-MM-dd hh:mm:ss')
            console.log('格式化后的最大时间 ' + newMaxDate)

            // 当前时间格式化
            let date1 = new Date()
            const newDate = formatDate(date1, 'yyyy-MM-dd hh:mm:ss')
            console.log('格式化后的当前时间 ' + newDate)

            // 最大时间与当前时间比较
            if (newMaxDate >= newDate) {
              this.isExpireTime = '已逾期'
            } else {
              this.isExpireTime = '未逾期'
            }
          })

        })
      },*/
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        //listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        selectUserListForStudent().then(response => {
          this.userList = response.userListForStudent;
          console.log(response)
          this.total = response.userListForStudent.length;
          this.loading = false;
        })
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.getList();
      },
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          userId: undefined,
          deptId: undefined,
          userName: undefined,
          nickName: undefined,
          password: undefined,
          phonenumber: undefined,
          email: undefined,
          sex: undefined,
          status: "0",
          remark: undefined,
          postIds: [],
          roleIds: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getTreeselect();
        getUser().then(response => {
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.open = true;
          this.title = "添加用户";
          this.form.password = this.initPassword;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getTreeselect();
        const userId = row.userId || this.ids;
        getUser(userId).then(response => {
          this.form = response.data;
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.form.postIds = response.postIds;
          this.form.roleIds = response.roleIds;
          this.open = true;
          this.title = "修改用户";
          this.form.password = "";
        });
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功，新密码是：" + value);
            }
          });
        }).catch(() => {});
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.userId != undefined) {
              updateUser(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addUser(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.userId || this.ids;
        this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
